package com.king.base.service.role.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.king.base.domain.role.RoleDept;
import com.king.base.domain.role.RoleMenu;
import com.king.base.msg.BaseResponseEntity;
import com.king.base.auth.utils.EntityUtils;
import com.king.base.domain.role.Role;
import com.king.base.mapper.role.RoleMapper;
import com.king.base.mapper.user.UserRoleMapper;
import com.king.base.service.role.RoleDeptService;
import com.king.base.service.role.RoleMenuService;
import com.king.base.service.role.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author TianYZ
 * @date 2019-06-15
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private RoleDeptService roleDeptService;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Override
    public IPage<Role> page(Page<Role> page, Role role) {
        List<Role> roles=baseMapper.page(page,role);
        return page.setRecords(roles);
    }
    @Override
    public List<Role> findByUserId(String userId) {
        List<Role> roleList=baseMapper.findByUserId(userId);
        return roleList;
    }

    @Override
    public Role findById(String id) {
       Role role=baseMapper.selectById(id);
       return role;
    }

    @Override
    public BaseResponseEntity createOrUpdate(Role role) {
        if (baseMapper.findByRoleCode(role) != null) {
            return new BaseResponseEntity(HttpStatus.BAD_REQUEST.value(),"编码重复!");
        }
        if(org.apache.commons.lang3.StringUtils.isNotBlank(role.getRoleId())){
            //根据需求修改
            if ("1".equals(role.getRoleId())) {
                return new BaseResponseEntity(HttpStatus.BAD_REQUEST.value(),"该角色不能被修改!");
            }
            EntityUtils.setUpdatedInfo(role);
        }else{
            EntityUtils.setCreateAndUpdateInfo(role);
        }
        if(super.saveOrUpdate(role)){
            //先删除所有菜单，后续考虑算法
            roleMenuService.deleteRoleMenuByRoleId(role.getRoleId());
            //重新添加菜单
            List<RoleMenu> list=new ArrayList<>();
            if(role.getMenuIds() !=null && role.getMenuIds().length>0){
                for(String menuId:role.getMenuIds()){
                    RoleMenu roleMenu=new RoleMenu(role.getRoleId(),menuId);
                    list.add(roleMenu);
                }
            }
            if(list.size()>0){
                roleMenuService.saveBatch(list);
            }
        }
        return new BaseResponseEntity();
    }

    @Override
    public BaseResponseEntity delete(String roleId) {

        // 根据实际需求修改
        if (roleId.equals("1")) {
            return new BaseResponseEntity(HttpStatus.BAD_REQUEST.value(),"该角色不能被删除");
        }

        //删除角色菜单关系
        roleMenuService.deleteRoleMenuByRoleId(roleId);
        // 删除人员角色关系
        userRoleMapper.deleteUserRole(null,roleId);
        //删除角色
        baseMapper.deleteById(roleId);
        return new BaseResponseEntity();
    }

    @Override
    public List<Role> getRoleTree() {

        List<Role> roleList = baseMapper.selectList(Wrappers.<Role>lambdaQuery().orderByAsc(Role::getSort));
        return roleList;
    }

    @Override
    public void updateRoleStatus(Role role) {
        updateById(role);
    }

    @Override
    public List<String> getRoleIdsByUserId(String userId) {
        List<Role> roles=findByUserId(userId);
        List<String> roleIds=new ArrayList<>();
        if(roles!=null && roles.size()>0){
            roles.forEach(role -> {
                roleIds.add(role.getRoleId());
            });
        }
        return roleIds;
    }

    @Override
    public void grantDataScope(Role role) {
        //先删除原有的权限
        roleDeptService.deleteRoleDeptByRoleId(role.getRoleId());
        if(role.getDeptIds() !=null && role.getDeptIds().length>0){
            List<RoleDept> list=new ArrayList<>();
            for(String s:role.getDeptIds()){
                list.add(new RoleDept(role.getRoleId(),s));
            }
            roleDeptService.saveBatch(list);
        }
        updateById(role);
    }

    @Override
    public List<String> selectDeptIdByRoleId(String roleId) {
        return roleDeptService.selectDeptIdByRoleId(roleId);
    }
}
